package medical.web.servlet;


import medical.database.DbUtil;
import medical.domain.menu.Menu;
import medical.domain.role.Role;
import medical.domain.user.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: tlgen
 * @Discription:
 */
public class UserServlet extends BaseServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);//使a标签发送post请求
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        String methodName = servletPath.substring(1);
        methodName = methodName.substring(0,methodName.length()-3);

        try {
            //反射获取methName
            Method method=getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            //利用反射调用方法
            method.invoke(this,request, response);

        }catch(Exception e) {

            response.sendRedirect("error.jsp");
        }
    }

    //显示所有用户信息
    private void list(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");


        List<User> userList = new ArrayList<User>(); // 创建一个list集合,用于装user集合
        Connection connection = DbUtil.getConn(); // 打开数据库连接
        String sql = "select userid, username, pwd, fullname, status from t_user";

        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet rs = preparedStatement.executeQuery();

            while (rs.next()) {
                Integer userid = rs.getInt("userid");
                String username = rs.getString("username");
                String pwd = rs.getString("pwd");
                String fullname = rs.getString("fullname");
                String status = rs.getString("status");
                User user = new User(); /// 实例化user
                user.setUserid(userid);
                user.setUsername(username);
                user.setPwd(pwd);
                user.setFullname(fullname);
                user.setStatus(status);
                userList.add(user);
            }
            request.setAttribute("userList", userList);
            request.getRequestDispatcher("/page/user/user_list.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //添加用户
    private void addUser(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        String fullname = request.getParameter("fullname");
        Integer status = Integer.parseInt(request.getParameter("status"));

            Connection conn = DbUtil.getConn(); /// 获得数据库连接

            String sql = "insert into t_user value(null,?,?,?,?);";

            try {
                PreparedStatement prtmt = conn.prepareStatement(sql); // 预编译
                prtmt.setString(1, username); // 给第一个? 传值
                prtmt.setString(2, pwd); // 给第二个? 传值
                prtmt.setString(3, fullname);
                prtmt.setInt(4, status);

                int resInt = prtmt.executeUpdate(); // 执行sql返回影响行数;
                request.setAttribute("resInt", resInt);

                request.getRequestDispatcher("/list.do").forward(request, response);

            } catch (Exception e) {
                e.printStackTrace();
            }
    }


//修改用户信息
    private void edit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Integer userid = Integer.parseInt(request.getParameter("userid"));
        Connection conn = DbUtil.getConn();
        String sql = "select * from t_user where userid = " + userid; // sql语句
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        ResultSet rs = preparedStatement.executeQuery();

            try {
                if (rs.next()) {

                    User user = new User();

                    user.setUserid(rs.getInt("userid"));
                    user.setUsername(rs.getString("username"));
                    user.setPwd(rs.getString("pwd"));
                    user.setFullname(rs.getString("fullname"));
                    user.setStatus(rs.getString("status"));

                    request.setAttribute("user", user);
                    request.getRequestDispatcher("/page/user/user_edit.jsp").forward(request, response);

                }
            }catch (SQLException e) {
                e.printStackTrace();
            }
    }

    //更新用户信息
    private void update(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Integer userid = Integer.parseInt(request.getParameter("userid"));
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        String fullname = request.getParameter("fullname");
        Integer status = Integer.parseInt(request.getParameter("status"));

        if (userid != null && username != null || pwd != null) {
            // 获得数据库连接
            Connection conn = DbUtil.getConn();
            String sql = "update t_user set username=?,pwd=?, fullname=?, status=? where userid=" + userid; // sql语句

            try {
                PreparedStatement prtmt = conn.prepareStatement(sql); // 预编译语句

                prtmt.setString(1, username); // 给第一个? 添加数据
                prtmt.setString(2, pwd); // 给第二个? 添加数据
                prtmt.setString(3, fullname); // 给第三个? 添加数据
                prtmt.setInt(4, status);

                int resInt = prtmt.executeUpdate(); // 执行sql返回影响行数;
                request.setAttribute("resInt", resInt);
                request.getRequestDispatcher("/list.do").forward(request, response);
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    //删除用户信息
    private void delete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String userid = request.getParameter("userid"); // 传入id;
        if (userid != null) {
            Connection conn = DbUtil.getConn();// 获得数据连接
            String sql = "delete from t_user where userid = ?";
            try {
                PreparedStatement prtmt = conn.prepareStatement(sql); // 预编译

                prtmt.setString(1, userid); // 给id赋值
                int resInt = prtmt.executeUpdate(); // 执行sql返回影响行数;
                request.setAttribute("resInt", resInt);
                request.getRequestDispatcher("/list.do").forward(request, response);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //用户功能权限
    private void user_list_menu(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");


        List<User> user_list_menus = new ArrayList<User>(); // 创建一个list集合,用于装user集合

        Set<Menu> menuSet = new HashSet<Menu>();

        Connection connection = DbUtil.getConn(); // 打开数据库连接
        /*select u.userid, u.username, e.menuid, e.menuname, e.url, e.level from (t_user u, t_menu e) inner join t_user_menu um on u.userid = um.userid and e.menuid = um.menuid*/
        String sql = "select u.userid, u.username, e.menuid, e.menuname, e.url, e.level from (t_user u, t_menu e) inner join t_user_menu um on u.userid = um.userid and e.menuid = um.menuid";

        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet rs = preparedStatement.executeQuery();

            while (rs.next()) {
                Integer userid = rs.getInt("userid");
                String username = rs.getString("username");
                String menuid = rs.getString("menuid");
                String menuname = rs.getString("menuname");
                String url = rs.getString("url");
                Integer level = rs.getInt("level");

                User user = new User();
                user.setUserid(userid);
                user.setUsername(username);

                Menu menu = new Menu();

                menu.setMenuid(menuid);
                menu.setMenuname(menuname);
                menu.setUrl(url);
                menu.setLevel(level);

                menuSet.add(menu);

               user.setMenus(menuSet);

                user_list_menus.add(user);
            }
            request.setAttribute("menus", menuSet);
            request.setAttribute("user_list_menus", user_list_menus);
            request.getRequestDispatcher("/page/menu/user_list_menu.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    //用户拥有角色权限
    private void user_list_role(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");


        List<User> user_role = new ArrayList<User>(); // 创建一个list集合,用于装user集合

        Set<Role> roleSet = new HashSet<Role>();

        Connection connection = DbUtil.getConn(); // 打开数据库连接
        /*select u.userid, u.username, u.fullname, r.roleid, r.rolename from (t_user u, t_role r) inner join
t_user_role ur on u.userid = ur.userid and r.roleid = ur.roleid */
        String sql = "select u.userid, u.username, u.fullname, r.roleid, r.rolename from (t_user u, t_role r) inner join \n" +
                "t_user_role ur on u.userid = ur.userid and r.roleid = ur.roleid ";

        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet rs = preparedStatement.executeQuery();

            while (rs.next()) {
                Integer userid = rs.getInt("userid");
                String username = rs.getString("username");
                String fullname = rs.getString("fullname");
                String roleid = rs.getString("roleid");
                String rolename = rs.getString("rolename");

                User user = new User();
                user.setUserid(userid);
                user.setUsername(username);
                user.setFullname(fullname);


                Role role = new Role();
                role.setRoleid(roleid);
                role.setRolename(rolename);

                roleSet.add(role);

                user.getRoles(roleSet);

                user_role.add(user);



            }
            request.setAttribute("roleSet", roleSet);
            request.setAttribute("user_role", user_role);
            request.getRequestDispatcher("/page/menu/user_list_role.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
